<?php

namespace App\Http\Controllers\admin\product;

use App\Http\Controllers\Controller;
use App\Models\product\ProductCourseModel;
use Illuminate\Http\JsonResponse;
use lxs\api\ApiResponse;

class MountCourseController extends Controller
{
    /**
     * 获取挂载教程列表页面数据
     */
    public function getMountCourseListData(): JsonResponse
    {
        $data = request()->input();

        $query = ProductCourseModel::where('deleted_at', 0);

        $lists = $query->orderBy('id', 'desc')->paginate($data['pageSize']);
        foreach ($lists as $k => $v) {
            $lists[$k]['course_type_name'] = ProductCourseModel::getCourseType($v['course_type']);
        }

        return ApiResponse::apiResponseData(200, '获取挂载教程列表页面数据成功', [
            'lists' => $lists,
        ]);
    }


    /**
     * 删除挂载教程表单提交
     */
    public function mountCourseDeleteSubmit(): JsonResponse
    {
        $id = request()->input('id');
        if (empty($id)) {
            return ApiResponse::apiResponseData(400, '参数错误', []);
        }
        $res = ProductCourseModel::where('id', $id)->update(['deleted_at' => time()]);
        if ($res) {
            return ApiResponse::apiResponseData(200, '删除成功', []);
        } else {
            return ApiResponse::apiResponseData(400, '删除失败', []);
        }
    }


    /**
     * 获取挂载教程表单数据
     */
    public function getMountCourseFormData(): JsonResponse
    {
        $id = request()->input('id');

        if ($id) {
            $list = ProductCourseModel::where('id', $id)->first();
            $list->course_type = ProductCourseModel::getCourseType($list->course_type);
        }

        $course_type_data = ProductCourseModel::getCourseType();
        return ApiResponse::apiResponseData(200, '获取挂载教程表单数据成功', [
            'list' => $list ?? [],
            'course_type_data' => $course_type_data,
        ]);
    }


    /**
     * 挂载教程表单提交
     */
    public function mountCourseFormSubmit(): JsonResponse
    {
        $post = request()->input();

        if (isset($post['id'])) {

            $post['course_type'] = ProductCourseModel::getCourseType($post['course_type']);

            $list = ProductCourseModel::find($post['id']);

        } else {
            $list = new ProductCourseModel();
        }

        $list->fill($post);
        if ($list->save()) {
            return ApiResponse::apiResponseData(200, '保存成功', []);
        } else {
            return ApiResponse::apiResponseData(400, '保存失败', []);
        }

    }


}
